<!-- 新增收货人 -->
<template>
  <view v-if="shenheStatus != 1 || !shenheAliStatus" class="addreceiving">
    <u-popup
      v-model="showAd"
      mode="bottom"
      :mask="false"
      :safe-area-inset-bottom="true"
    >
      <view class="picker-view-title">
        <div class="left" @click="showAd = false">取消</div>
        <div class="right" @click="confirm">确定</div>
      </view>
      <picker-view
        indicator-style="height:50rpx;"
        :value="defaultIndex"
        @change="selectChange"
        class="picker-view"
      >
        <picker-view-column>
          <view
            class="item"
            v-for="(item, index) in districtList_1"
            :key="index"
            >{{ item.name }}</view
          >
        </picker-view-column>
        <picker-view-column>
          <view
            class="item"
            v-for="(item, index) in districtList_2"
            :key="index"
            >{{ item.name }}</view
          >
        </picker-view-column>
        <picker-view-column>
          <view
            class="item"
            v-for="(item, index) in districtList_3"
            :key="index"
            >{{ item.name }}</view
          >
        </picker-view-column>
        <picker-view-column v-if="districtList_4.length > 0">
          <view
            class="item"
            v-for="(item, index) in districtList_4"
            :key="index"
            >{{ item.name }}</view
          >
        </picker-view-column>
        <picker-view-column v-if="districtList_5.length > 0">
          <view
            class="item"
            v-for="(item, index) in districtList_5"
            :key="index"
            >{{ item.name }}</view
          >
        </picker-view-column>
      </picker-view>
    </u-popup>

    <view class="add-msg">
      <view class="add-msg-list btm">
        <view>{{ $t("my.consignee") }}</view>
        <input
          type="text"
          v-model="name"
          :placeholder="$t('my.consigneeName')"
        />
      </view>
      <view class="add-msg-list btm">
        <view>{{ $t("my.phone") }}</view>
        <input
          @input="phone = phone.replace(/[^\d]/g, '')"
          maxlength="11"
          type="number"
          v-model="phone"
          :placeholder="$t('my.phoneNumber')"
        />
      </view>
      <view class="add-msg-list-three btm">
        <view @click="showAd = true">
          <view>{{ $t("my.region") }}</view>
          <input
            style="pointer-events: none"
            type="text"
            v-model="position"
            disabled
            :placeholder="$t('user.area')"
          />
        </view>
        <view>
          <u-icon name="map-fill"></u-icon>
          <view @click="getPosition">{{ $t("my.positioning") }}</view>
        </view>
      </view>
      <view class="add-msg-list btm">
        <view>{{ $t("my.detail") }}</view>
        <textarea v-model="details" :placeholder="$t('my.street')" />
      </view>
    </view>

    <view class="default-adress">
      <view>
        <view>{{ $t("my.default") }}</view>
        <view>{{ $t("my.warning") }}</view>
      </view>
      <switch
        :checked="isSetDefaultAdd"
        @change="changeswitch"
        color="rgb(25,190,106)"
        style="transform: scale(0.8)"
      />
    </view>

    <view class="ocr">
      <view class="title">智能填写</view>

      <view class="con">
        <textarea
          v-model="content"
          placeholder="粘贴收货信息到此处，将自动识别姓名/电话/地址"
        ></textarea>

        <view class="ocr-fd">
          <view class="ocr-fd-let">
            <view class="icon" @click="ocr">
              <i class="icon-camera iconfont"></i>
              <view class="text">图片识别</view>
            </view>
          </view>

          <view class="ocr-fd-rig">
            <view class="submit" @click="submit">粘贴并识别</view>
          </view>
        </view>
      </view>
    </view>

    <view class="tools-pof">
      <view class="save" @click="onSave">{{ $t("my.save") }}</view>
    </view>
  </view>
  <Shenhe v-else-if="shenheStatus == 1"></Shenhe>
</template>

<script>
import Shenhe from "@/components/shenhe/shenhe";
import { addressRecognition } from "@/api/user";
var district = [];
export default {
  components: { Shenhe },
  data() {
    return {
      showAd: false,
      name: "",
      phone: "",
      province_id: "",
      city_id: "",
      district_id: "",
      town_id: "",
      village_id: "",
      longitude: "",
      latitude: "",
      position: "",
      details: "",
      isSetDefaultAdd: true,
      districtList: [],
      address_id: "",

      districtList_1: [],
      districtList_2: [],
      districtList_3: [],
      districtList_4: [],
      districtList_5: [],
      defaultIndex: [0, 0, 0, 0, 0],

      content: ""
    };
  },
  computed: {},
  onLoad(option) {
    uni.setNavigationBarTitle({
      title: this.$t("title.addReceiving")
    });

    this.getDistrict(async () => {
      if (option.id) {
        this.address_id = option.id;
        this.getDetailsById(option.id);
      } else {
        let session_addr = uni.getStorageSync("session_addr");
        if (session_addr) {
          let { address_content, address_name, address_phone, address_poi } =
              session_addr,
            { city, detail, location, province, town } = address_content,
            { lat, lng } = address_poi;

          this.name = address_name;
          this.phone = address_phone;
          this.position = `${province},${city},${town}`;
          this.details = detail || location;
          this.latitude = lat;
          this.longitude = lng;

          let province_id = district.find((el) => el.name == province),
            province_index = district.findIndex((el) => el.name == province),
            city_id = province_id.cityAll.find((el) => el.name == city),
            city_index = province_id.cityAll.findIndex((el) => el.name == city),
            district_id = city_id.districtAll.find((el) => el.name == town),
            district_index = city_id.districtAll.findIndex(
              (el) => el.name == town
            );

          this.defaultIndex = [province_index, city_index, district_index];
          this.province_id = province_id.id;
          this.city_id = city_id.id;
          this.district_id = district_id.id;
        }
      }
    });
  },
  methods: {
    setAddressList(list = []) {
      let cityList,
        districtList,
        provinceIndex = 0,
        cityIndex = 0,
        districtIndex = 0;

      if (list && list.length) {
        cityList = district.find((el) => String(list[0]) === el.id).cityAll;
        districtList = cityList.find(
          (el) => String(list[1]) === el.id
        ).districtAll;

        provinceIndex = district.findIndex((el) => String(list[0]) === el.id);
        cityIndex = cityList.findIndex((el) => String(list[1]) === el.id);
        districtIndex = districtList.findIndex(
          (el) => String(list[2]) === el.id
        );
      } else {
        let cityAllItem = JSON.parse(JSON.stringify(district[0].cityAll));
        cityList = cityAllItem;
        districtList = cityList[0].districtAll;
      }

      this.districtList_2 = JSON.parse(JSON.stringify(cityList)).map((el) => {
        delete el.districtAll;
        return el;
      });
      this.districtList_3 = districtList;
      this.defaultIndex = [provinceIndex, cityIndex, districtIndex];
    },

    selectChange(e) {
      let indexs = e.detail.value;
      let yDefaultIndex = JSON.parse(JSON.stringify(this.defaultIndex));
      if (yDefaultIndex[0] != indexs[0]) {
        this.defaultIndex = [indexs[0], 0, 0, 0, 0];
      } else if (yDefaultIndex[1] != indexs[1]) {
        this.defaultIndex = [indexs[0], indexs[1], 0, 0, 0];
      } else if (yDefaultIndex[2] != indexs[2]) {
        (this.defaultIndex = [indexs[0], indexs[1], indexs[2], 0]), 0;
      } else if (yDefaultIndex[3] != indexs[3]) {
        this.defaultIndex = [indexs[0], indexs[1], indexs[2], indexs[3], 0];
      } else if (yDefaultIndex[4] != indexs[4]) {
        this.defaultIndex = [
          indexs[0],
          indexs[1],
          indexs[2],
          indexs[3],
          indexs[4]
        ];
      }
      this.districtList_2 = district[this.defaultIndex[0]].cityAll;
      this.districtList_3 =
        district[this.defaultIndex[0]].cityAll[
          this.defaultIndex[1]
        ].districtAll;
      this.districtList_4 =
        district[this.defaultIndex[0]].cityAll[
          this.defaultIndex[1]
        ].districtAll[this.defaultIndex[2]].townAll;
      if (this.districtList_4.length > 0) {
        this.districtList_5 =
          district[this.defaultIndex[0]].cityAll[
            this.defaultIndex[1]
          ].districtAll[this.defaultIndex[2]].townAll[
            this.defaultIndex[3]
          ].villageAll;
      } else {
        this.districtList_5 = [];
      }
    },
    async getDistrict(fn) {
      try {
        var res = await this.$allrequest.user.get_district({});
        district = JSON.parse(JSON.stringify(res.data));

        this.districtList_1 = res.data.map((item) => {
          delete item.cityAll;
          return item;
        });

        this.setAddressList();
        fn && fn();
      } catch (e) {
        //TODO handle the exception
      }
    },

    async getDetailsById(id) {
      try {
        const res = await this.$allrequest.user.address_details({
          id
        });
        this.name = res.data.name;
        this.phone = res.data.mobile;
        this.details = res.data.detail;
        this.latitude = res.data.latitude;
        this.longitude = res.data.longitude;
        this.province_id = res.data.district.province.id;
        this.city_id = res.data.district.city.id;
        this.district_id = res.data.district.district.id;
        this.town_id = res.data.district.town.id;
        this.village_id = res.data.district.village.id;
        this.isSetDefaultAdd = res.data.is_default == 1;
        this.position =
          res.data.district.province.name +
          res.data.district.city.name +
          res.data.district.district.name +
          res.data.district.town.name +
          res.data.district.village.name;

        let { province_id, city_id, district_id, town_id, village_id } = this;
        this.setAddressList([
          province_id,
          city_id,
          district_id,
          town_id,
          village_id
        ]);
      } catch (e) {
        //TODO handle the exception
      }
    },
    async saveAdd() {
      const params = {
        address_id: this.address_id,
        name: this.name,
        mobile: this.phone,
        province_id: this.province_id,
        city_id: this.city_id,
        district_id: this.district_id,
        town_id: this.town_id,
        village_id: this.village_id,
        detail: this.details,
        longitude: this.longitude + "",
        latitude: this.latitude + ""
      };
      try {
        const res = await this.$allrequest.user.address_save(params);
        if (res.code != 0) {
          this.$utils.toast(res.msg);
          return false;
        }
        if (this.isSetDefaultAdd) {
          this.setDefaultAdd(res.data.address_id);
        }
        this.$utils.goBack();
      } catch (e) {
        //TODO handle the exception
      }
    },
    async setDefaultAdd(id) {
      try {
        await this.$allrequest.user.address_set_default({
          address_id: id ? id : this.address_id
        });
      } catch (e) {
        //TODO handle the exception
      }
    },
    onSave() {
      if (!this.name) {
        this.$utils.toast(this.$t("my.consigneeName"));
        return;
      }
      if (!this.phone) {
        this.$utils.toast(this.$t("my.phoneNumber"));
        return;
      } else if (!/^[1][3,4,5,6,7,8,9][0-9]{9}$/.test(this.phone)) {
        this.$utils.toast(this.$t("login.inputPhoneNumber"));
        return;
      }
      if (!this.province_id) {
        this.$utils.toast(this.$t("my.chooseRegion"));
        return;
      }
      // #ifndef APP-PLUS
      // if (!this.latitude) {
      //   this.$utils.toast(this.$t("my.choosePosition"));
      //   return;
      // }
      // #endif
      if (!this.details) {
        this.$utils.toast(this.$t("my.fillDetail"));
        return;
      }
      this.saveAdd();
    },
    confirm() {
      this.showAd = false;

      let val = this.defaultIndex;
      let i1 = val[0];
      let i2 = val[1];
      let i3 = val[2];
      let i4 = val[3];
      let i5 = val[5];
      this.province_id = this.districtList_1[i1].id;
      this.city_id = this.districtList_2[i2].id;
      this.district_id = this.districtList_3[i3].id;
      if (this.districtList_4.length > 0) {
        this.town_id = this.districtList_4[i4].id;
      } else {
        this.town_id = 0;
      }
      if (this.districtList_5.length > 0) {
        if (i5) {
          this.village_id = this.districtList_5[i5].id;
        } else {
          this.village_id = this.districtList_5[0].id;
        }
      } else {
        this.village_id = 0;
      }
      this.position = [];
      this.position[0] = this.districtList_1[i1].name;
      this.position[1] = this.districtList_2[i2].name;
      this.position[2] = this.districtList_3[i3].name;
      if (this.districtList_4.length > 0) {
        this.position[3] = this.districtList_4[i4].name;
      }
      if (this.districtList_5.length > 0) {
        if (i5) {
          this.position[4] = this.districtList_5[i5].name;
        } else {
          this.position[4] = this.districtList_5[0].name;
        }
      }
      this.position = this.position.join(",");
    },
    async getPosition() {
      const apiRes = await this.$store.dispatch("getLocation");
      if (apiRes.longitude) {
        uni.chooseLocation({
          success: (res) => {
            this.longitude = res.longitude;
            this.latitude = res.latitude;
            this.details = res.name;
            this.getAddress(res.address + res.name);
          },
          fail: () => {
            this.$u.toast(this.$t("my.failPosition"));
          }
        });
      }
    },
    getAddress(address) {
      this.$allrequest.classification
        .addressSmart({
          address
        })
        .then((res) => {
          if (res.code == 0) {
            this.province_id = res.data.province_id;
            this.city_id = res.data.city_id;
            this.district_id = res.data.region_id;
            this.position = res.data.province + res.data.city + res.data.region;
          }
        });
    },
    changeswitch(val) {
      this.isSetDefaultAdd = val.target.value;
    },

    ocr() {
      this.$utils.uploadImage(1, async (url) => {
        const res = await this.$allrequest.merchant.analysis(
          {
            type: 4,
            url
          },
          true
        );
        if (!res.code) {
          this.content = res.data.str;
        }
      });
    },

    async submit() {
      let con = "";
      if (!this.content) {
        let res = await uni.getClipboardData();
        con = res[1]?.data || "";

        this.content = con;
      } else {
        con = this.content;
      }

      if (!con) {
        this.$utils.toast("请复制或识别需要的内容");
        return;
      }

      const result = await addressRecognition(
        {
          content: con
        },
        true
      );
      if (!result.code) {
        const {
          province_id,
          city_id,
          region_id,
          addr,
          city,
          province,
          region,
          name,
          mobile,
          latitude,
          longitude
        } = result.data;

        this.name = name;
        this.phone = mobile;
        this.position = `${province},${city},${region}`;
        this.details = addr;
        this.latitude = latitude;
        this.longitude = longitude;

        this.province_id = province_id;
        this.city_id = city_id;
        this.district_id = region_id;

        this.setAddressList([province_id, city_id, region_id, 0, 0]);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.addreceiving {
  padding: 24rpx 24rpx 200rpx;
  min-height: 100vh;
  background-color: #f2f2f2;
}

.add-msg {
  background-color: #ffffff;
  border-radius: 24rpx;
  padding-left: 30rpx;

  .btm {
    border-top: 1rpx solid #f0f0f0;
  }

  .add-msg-list {
    padding: 36rpx 0rpx;
    display: flex;
    align-items: flex-start;
    padding-right: 140rpx;

    view {
      width: 140rpx;
      font-size: 28rpx;
      color: #262626;
    }

    input {
      flex: 1;
      font-size: 28rpx;
    }

    textarea {
      flex: 1;
      height: 130rpx;
    }
  }

  .add-msg-list-three {
    padding: 36rpx 31rpx 36rpx 0rpx;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    > view:first-child {
      flex: 1;
      display: flex;
      flex-direction: row;
      padding-right: 30rpx;

      view {
        width: 140rpx;
        font-size: 28rpx;
        color: #262626;
      }

      input {
        flex: 1;
        font-size: 28rpx;
      }
    }

    > view:last-child {
      display: flex;
      align-items: center;

      image {
        width: 20rpx;
        height: 28rpx;
        background-color: red;
      }

      view {
        margin-left: 10rpx;
        font-size: 28rpx;
        color: #262626;
      }
    }
  }
}

.default-adress {
  margin-top: 20rpx;
  padding: 42rpx 20rpx 34rpx 31rpx;
  display: flex;
  background-color: #ffffff;
  border-radius: 24rpx;
  align-items: center;
  justify-content: space-between;

  > view {
    view:first-child {
      font-size: 28rpx;
      color: #262626;
    }

    view:last-child {
      margin-top: 20rpx;
      font-size: 22rpx;
      color: #262626;
    }
  }
}

.save {
  height: 96rpx;
  border-radius: 48rpx;
  color: #ffffff;
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  line-height: 96rpx;
  background: linear-gradient(90deg, #f3150c, #f14b0c);
}

.delete {
  margin: 40rpx auto 0rpx;
  width: 676rpx;
  height: 94rpx;
  border-radius: 48rpx;
  border: 1rpx solid #c7c7c7;
  color: #262626;
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  line-height: 94rpx;
  background-color: #ffffff;
}

.picker-view-title {
  padding: 20rpx;
  font-size: 28rpx;
  color: #1aa034;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .left {
    color: #999;
  }
}

.picker-view {
  width: 750rpx;
  height: 500rpx;
}
.item {
  height: 50rpx;
  line-height: 50rpx;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.tools-pof {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  padding: 10rpx 30rpx calc(env(safe-area-inset-bottom) + 10rpx);
  background: #fff;
}

.ocr {
  margin-top: 20rpx;
  padding: 0 24rpx 24rpx;
  background: #fff;
  border-radius: 20rpx;

  .title {
    padding: 24rpx 0;
    font-size: 30rpx;
    color: #262626;
    border-bottom: 2rpx solid #f8f8f8;
  }

  textarea {
    padding: 24rpx 0;
    height: 100rpx;
    font-size: 28rpx;
  }

  .ocr-fd {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
  }

  .ocr-fd-let {
    .icon {
      display: flex;
      align-items: center;
    }

    .icon-camera {
      font-size: 40rpx;
    }
  }

  .ocr-fd-rig {
    .submit {
      font-weight: bold;
      color: #f0250e;
    }
  }
}
</style>
